package com.piggy.sys.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.utils.StringUtils;
import com.piggy.common.core.utils.poi.ExcelUtil;
import com.piggy.common.core.web.controller.BaseController;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.common.log.annotation.Log;
import com.piggy.common.log.enums.BusinessType;
import com.piggy.common.satoken.annotation.Inner;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.logi.sys.api.RemoteLogiDeptService;
import com.piggy.logi.sys.api.RemoteLogiUserService;
import com.piggy.logi.sys.api.bo.LogiSysDeptExtCusEditBo;
import com.piggy.logi.sys.api.domain.LogiSysDept;
import com.piggy.logi.sys.api.domain.LogiSysUser;
import com.piggy.logi.sys.api.vo.LogiSysDeptExtVo;
import com.piggy.oss.cloud.OSSFactory;
import com.piggy.sys.api.domain.SysRole;
import com.piggy.sys.api.domain.SysUser;
import com.piggy.sys.api.model.LoginUser;
import com.piggy.sys.enums.OrgTypeEnum;
import com.piggy.sys.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author shark
 */
@Api(value = "用户管理", tags = {"用户管理"})
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysPostService postService;

    @Resource
    private ISysPermissionService permissionService;

    @Resource
    private RemoteLogiUserService logiUserService;

    @Resource
    private RemoteLogiDeptService logiDeptService;

    /**
     * 获取用户列表
     */
    //@SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    //@SaCheckPermission("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) throws IOException {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    //@SaCheckPermission("system:user:import")
    @PostMapping("/importData")
    public R importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return R.ok(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/info/{username}")
    public R<LoginUser<SysUser>> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(sysUser);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/phone/{phone}")
    public R<LoginUser<SysUser>> phone(@PathVariable("phone") String phone) {
        SysUser logiSysUser = userService.selectUserByPhone(phone);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/email/{email}")
    public R<LoginUser<SysUser>> email(@PathVariable("email") String email) {
        SysUser logiSysUser = userService.selectUserByEmail(email);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    private R<LoginUser<SysUser>> userInfo(SysUser user) {
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user.getUserId());
        LoginUser<SysUser> sysUserVo = new LoginUser<>();
        sysUserVo.setSysUser(user);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/sys/{username}")
    public R<SysUser> sysUser(@PathVariable("username") String username) {

        if (StrUtil.isBlank(username)) {
            return R.fail("用户名不能为空");
        }

        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名不存在");
        }

        return R.ok(sysUser);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R getInfo() {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        Map<String, Object> ajax = new HashMap<>(3);
        SysUser user = userService.selectUserById(userId);
        if (ObjectUtil.isEmpty(user)) {
            return R.fail("用户不存在");
        }
        String avatar = OSSFactory.build().buildUrl(user.getAvatar());
        user.setAvatar("avatar");
        ajax.put("user", user);
        ajax.put("roles", roles);
        if(SecurityUtils.isAdmin(userId)){
            //999 超级管理员
            ajax.put("orgType",OrgTypeEnum.SYSADMIN.getCode());//返回给前端判断用
            ajax.put("orgTypeName",OrgTypeEnum.SYSADMIN.getInfo());
        }else{
            //0 未知
            ajax.put("orgType", OrgTypeEnum.UNKNOWN.getCode());
            ajax.put("orgTypeName",OrgTypeEnum.UNKNOWN.getInfo());
        }
        ajax.put("permissions", permissions);
        return R.ok(ajax);
    }

    /**
     * 根据用户编号获取详细信息
     */
    ////@SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public R<SysUser> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        /*Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put("user", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }*/
        if (Objects.isNull(userId)) {
            userId = SecurityUtils.getUserId();
        }
        SysUser user = userService.selectUserById(userId);
        userService.checkUserDataScope(userId);
        List<SysRole> roles = roleService.selectRoleAll();
        user.setRoles(roles);
        user.setPosts(postService.selectPostAll());
        user.setPostIds(postService.selectPostListByUserId(userId));
        user.setRoleIds(roleService.selectRoleIdsByUserId(userId));
        return R.ok(user);

    }

    /**
     * 根据用户编号获取详细信息
     */
    ////@SaCheckPermission("system:user:query")
    @GetMapping(value = {"infoById/", "infoById/{userId}"})
    public R<Map<String, Object>> getInfoById(@PathVariable(value = "userId", required = false) Long userId) {
        Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SecurityUtils.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put("user", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return R.ok(ajax);
    }

    /**
     * 新增用户
     */
    //@SaCheckPermission("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    //@SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    //@SaCheckPermission("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    //@SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    //@SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @Inner
    @GetMapping("/getUser/{deptId}")
    public R<List<SysUser>> getUserByDeptId(@PathVariable(value = "deptId", required = false) Long deptId) {
        return R.ok(userService.getUserByDeptId(deptId));
    }

    @Inner
    @GetMapping("/getUserByDeptIds")
    public R<List<SysUser>> getUserByDeptIds(@RequestParam("deptIds") List<Long> deptIds) {
        return R.ok(userService.getUserByDeptIds(deptIds));
    }

    @Inner
    @PostMapping("/queryUserAll")
    public R<List<SysUser>> queryUserAll() {
        return R.ok(userService.queryUserAll());
    }

    @Inner
    @GetMapping("/getUsersByPhoneNumber")
    public R<List<SysUser>> getUsersByPhoneNumber(@RequestParam("phoneNumber") String phoneNumber) {
        return R.ok(userService.getUsersByPhoneNumber(phoneNumber));
    }
    @Inner
    @GetMapping("/getUserByID")
    public R<SysUser> getUserByID(@RequestParam("userId") Long userId) {
        return R.ok(userService.getById(userId));
    }

    /**
     * 根据用户编号获取授权角色
     */
    //@SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public R authRole(@PathVariable("userId") Long userId)
    {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", SecurityUtils.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return R.ok(map);
    }

    /**
     * 用户授权角色
     */
    //@SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public R insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @Log(title = "查询物流系统未审核账号")
    @ApiOperation(value = "查询物流系统未审核账号")
    @PostMapping("/logiUser/unchecked")
    public TableDataInfo<LogiSysUser> unchecked(@RequestBody LogiSysUser user) {
        //user.setCheckStatus("0");
        user.setParentId(0L);
        user.setNotUserId(1L);
        user.setRoleKeys(Sets.newHashSet(SecurityUtils.AdminRoleEnum.ADMIN.getRole()));
        return logiUserService.innerList(user, SecurityConstants.INNER);
    }

    @ApiOperation(value = "新增服务商主用户")
    @PostMapping("/logiUser/bossAddUser")
    public R bossAddUser(@RequestBody LogiSysUser user) {
        return logiUserService.bossAdd(user, SecurityConstants.INNER);
    }

    @ApiOperation(value = "新增服务商")
    @PostMapping("/logiUser/bossAddDept")
    public R<LogiSysDeptExtVo> bossAddDept(@RequestBody LogiSysDeptExtCusEditBo dept) {
        dept.setParentId(0L);
        dept.setAncestors(null);
        return logiDeptService.bossAdd(dept, SecurityConstants.INNER);
    }

    @Log(title = "编辑服务商", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "编辑服务商")
    @PostMapping("/logiUser/bossEditDept")
    public R<LogiSysDeptExtVo> bossEditDept(@RequestBody LogiSysDeptExtCusEditBo dept) {
        dept.setParentId(0L);
        dept.setAncestors(null);
        return logiDeptService.bossEdit(dept, SecurityConstants.INNER);
    }

    @Log(title = "服务商启用", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "服务商启用")
    @PostMapping("/logiUser/enableBossDept/{deptId}")
    public R<LogiSysDeptExtVo> enableBossDept(@PathVariable("deptId")Long deptId) {
        LogiSysDeptExtCusEditBo dept = new LogiSysDeptExtCusEditBo();
        dept.setParentId(0L);
        dept.setStatus("0");
        dept.setAncestors(null);
        dept.setDeptId(deptId);
        return logiDeptService.bossEdit(dept, SecurityConstants.INNER);
    }

    @Log(title = "服务商禁用", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "服务商禁用")
    @PostMapping("/logiUser/disableBossDept/{deptId}")
    public R<LogiSysDeptExtVo> disableBossDept(@PathVariable("deptId")Long deptId) {
        LogiSysDeptExtCusEditBo dept = new LogiSysDeptExtCusEditBo();
        dept.setParentId(0L);
        dept.setStatus("1");
        dept.setAncestors(null);
        dept.setDeptId(deptId);
        return logiDeptService.bossEdit(dept, SecurityConstants.INNER);
    }

    @Log(title = "查询服务商列表")
    @ApiOperation(value = "查询服务商列表")
    @PostMapping("/logiUser/bossRootList")
    public TableDataInfo<LogiSysDeptExtVo> bossRootList(@RequestBody LogiSysDept dept) {
        return logiDeptService.rootList(dept, SecurityConstants.INNER);
    }

    @ApiOperation(value = "删除服务商")
    @DeleteMapping("/logiUser/removeRoot/{deptId}")
    public R removeRoot(@PathVariable("deptId")Long deptId) {
        return logiDeptService.removeRoot(deptId, SecurityConstants.INNER);
    }

}
